package org.ucas.faker.web.entity.patents;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.ucas.faker.web.utils.model.RawPatent;
import org.ucas.faker.web.entity.IdEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;

@Entity
@Table(name = "patent_meta", indexes = {
    @Index(name = "source_index", columnList = "source,source_id", unique = true)
})
public class PatentMeta extends IdEntity implements Patentable {

  public static enum Source {
    WX,
    FILE;

    public static Source of(String str) {
      switch (str.toUpperCase()) {
        case "WX":
          return WX;
        case "FILE":
          return FILE;
        default:
          return WX;
      }
    }
  }

  @Column(name = "source", nullable = false, columnDefinition = "int(11) default 0")
  private Source source = Source.WX;

  @Column(name = "source_id")
  private String sourceId;

  @Column(name = "parsed")
  private boolean parsed = false;

  @Column(name = "detail")
  private String detail; // Json格式的详情字符串，自定义信息

  @Column(name = "score")
  private Integer score = 0;

  public void of(RawPatent patent, boolean overwrite) {
    if(overwrite || this.id == null) this.id = patent.id;
    if(overwrite || this.source == null) this.source = Source.of(patent.getSource());
    if(overwrite || this.sourceId == null) this.sourceId = patent.sourceId;
  }

  public void to(RawPatent patent, boolean overwrite) {
    if(overwrite || patent.id == null) patent.id = this.id;
    if(overwrite || patent.source == null) patent.source = this.source.toString();
    if(overwrite || patent.sourceId == null) patent.sourceId = this.sourceId;
  }

  public Source getSource() {
    return source;
  }

  public void setSource(Source source) {
    this.source = source;
  }

  public String getSourceId() {
    return sourceId;
  }

  public void setSourceId(String sourceId) {
    this.sourceId = sourceId;
  }

  public boolean isParsed() {
    return parsed;
  }

  public void setParsed(boolean parsed) {
    this.parsed = parsed;
  }

  public Integer getScore() {
    return score;
  }

  public void setScore(Integer score) {
    this.score = score;
  }

  public String getDetail() {
    return detail;
  }

  public void setDetail(String detail) {
    this.detail = detail;
  }

  @SuppressWarnings("unchecked")
  public <T> T detail(String key) {
    if(key == null || detail == null) return null;
    JSONObject json = JSON.parseObject(detail);
    return (T) json.get(key);
  }
}
